package com.zjdiepu.www.biz.yw;

import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SysParamsType;
import com.zjdiepu.www.commpent.mapper.yw.AbstractYwBusinessLoanVoNewMapper;
import com.zjdiepu.www.dao.base.DpBaseDataDictionaryMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarMapper;
import com.zjdiepu.www.dao.yw.YwBusinessLoanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.system.IBaseSysParamsService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanService;
import com.zjdiepu.www.model.base.dto.DpBaseDataDictionary;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.ext.YwBusinessLoanExt;
import com.zjdiepu.www.util.CarHelper;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 贷款信息Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年04月24日 14时45分<br/>
 * @since 1.0<br/>
 */
@Service
public class YwBusinessLoanServiceImpl extends BaseService implements IYwBusinessLoanService {
	public static final Logger logger = LoggerFactory.getLogger(YwBusinessLoanServiceImpl.class);

	@Autowired
	private YwBusinessLoanMapper ywBusinessLoanMapper;
	@Autowired
	private DpBaseDataDictionaryMapper dpBaseDataDictionaryMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private YwBusinessCarMapper ywBusinessCarMapper;
	@Autowired
	private IBaseSysParamsService baseSysParamsService;
	@Autowired
	private ICachedDictionaryService cachedDictionaryService;
	@Autowired
	private AbstractYwBusinessLoanVoNewMapper ywBusinessLoanVoMapper;
	
	@Override
	public void saveUpdateAndDelete(YwBusinessLoan ywBusinessLoan, OperateType operType) {
		switch (operType) {
		case add:
			ywBusinessLoan.initInsertData(ywBusinessLoan.getModifier(), ywBusinessLoan.getModifierName());
			ywBusinessLoanMapper.insert(ywBusinessLoan);
			break;
		case edit:
			ywBusinessLoan.initUpdateData(ywBusinessLoan.getModifier(), ywBusinessLoan.getModifierName());
			// 影响的记录数
			int updateCount = ywBusinessLoanMapper.updateByPrimaryKeySelective(ywBusinessLoan);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			ywBusinessLoan.initDeleteData(ywBusinessLoan.getModifier(), ywBusinessLoan.getModifierName());
			// 影响的记录数
			int deleteCount = ywBusinessLoanMapper.updateByPrimaryKeySelective(ywBusinessLoan);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
		String carType = ywBusinessLoan.getCarType();
		String carId = ywBusinessLoan.getCarId();
		if(StringUtils.isNotBlank(carType) && StringUtils.isNotBlank(carId)) {
			YwBusinessCar ywBusinessCar = new YwBusinessCar();
			ywBusinessCar.setId(carId);
			ywBusinessCar.setCarType(carType);
			ywBusinessCarMapper.updateByPrimaryKeySelective(ywBusinessCar);
		}
		if(ywBusinessLoan.getLoanAmount() != null || ywBusinessLoan.getSignLoanAmount() != null) {
			YwBusiness ywBusiness = new YwBusiness();
			ywBusiness.setId(ywBusinessLoan.getBusiId());
			ywBusiness.setRealLoanAmount(ywBusinessLoan.getLoanAmount());
			ywBusiness.setSignLoanAmount(ywBusinessLoan.getSignLoanAmount());
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		}
	}
	
	@Override
	public List<YwBusinessLoan> selectByExt(YwBusinessLoanExt ywBusinessLoanExt) {
		return ywBusinessLoanMapper.selectByExt(ywBusinessLoanExt);
	}
	
	@Override
	public int countByExt(YwBusinessLoanExt ywBusinessLoanExt){
		return ywBusinessLoanMapper.countByExt(ywBusinessLoanExt);
	}
	
	@Override
	public YwBusinessLoan selectById(String id) {
		return ywBusinessLoanMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			ywBusinessLoanMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(YwBusinessLoan ywBusinessLoan) {
		return ywBusinessLoanMapper.countRefined(ywBusinessLoan);
	}

	@Override
	public YwBusinessLoan selectRefined(YwBusinessLoan ywBusinessLoan) {
		return ywBusinessLoanMapper.selectRefined(ywBusinessLoan);
	}

	@Override
	public boolean repeat(YwBusinessLoan ywBusinessLoan) {
		int count = countRefined(ywBusinessLoan);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(ywBusinessLoan.getId())) {
			return true;
		}
		YwBusinessLoan dbItem = selectRefined(ywBusinessLoan);
		if(null == dbItem) {
			return false;
		}
		return !ywBusinessLoan.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return ywBusinessLoanMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public ApiResponse checkIfNeedCalculation(YwBusinessLoan ywBusinessLoan) {
		YwBusinessLoanExt ywBusinessLoanExt = new YwBusinessLoanExt();
		ywBusinessLoanExt.setBusiId(ywBusinessLoan.getBusiId());
		ywBusinessLoanExt.setCarId(ywBusinessLoan.getCarId());
		ywBusinessLoanExt.setBaseWhere();
		ywBusinessLoanExt.setRows(1);
		List<YwBusinessLoan> oldYwBusinessLoans = ywBusinessLoanMapper.selectByExt(ywBusinessLoanExt);
		if(oldYwBusinessLoans.size() > 0){ //有计算记录
			YwBusinessLoan oldYwBusinessLoan = oldYwBusinessLoans.get(0);
//			Integer loanMonth = ywBusinessLoan.getLoanMonth();
//			String loanBank = ywBusinessLoan.getLoanBank();
//			Double currentBankRate = calculationBankRate(loanMonth, loanBank);
			Double currentBankRate = ywBusinessLoan.getBankRate();
			
			YwBusinessCar ywBusinessCar = ywBusinessCarMapper.selectByPrimaryKey(ywBusinessLoan.getCarId());
			String oldCarType = ywBusinessCar.getCarType();
			if(CarHelper.hasCalculation(ywBusinessLoan, oldYwBusinessLoan, currentBankRate, oldCarType)){ //已经估价，且条件一致
				return ApiResponse.fail(ResultFlagType.CALCULATION_REPEAT);
			} else { //重新估价
				return ApiResponse.success(oldYwBusinessLoan.getId());
			}
		} else { //没有估价
			return ApiResponse.success(null); 
		}
	}

	@Override
	public void calculation(YwBusinessLoan ywBusinessLoan) {
		String loanType = ywBusinessLoan.getLoanType();
		Double bankRate = ywBusinessLoan.getBankRate();
		String loanBank = ywBusinessLoan.getLoanBank();
		/*@update 2017-11-16 兼容App老版本 用于获取银行利率*/
		if(null == bankRate || bankRate == 0.0) {
			Integer loanMonth = ywBusinessLoan.getLoanMonth();
			bankRate = calculationBankRate(loanMonth, loanBank);
			ywBusinessLoan.setBankRate(bankRate);
		}
		if("04".equals(loanType)){
			if("ICBC".equals(loanBank)) {
				ywBusinessLoanVoMapper.calculationPx(ywBusinessLoan);
			} else if("TJICBC".equals(loanBank)) {
				ywBusinessLoanVoMapper.calculationTjPx(ywBusinessLoan); //天津平息
			}
			
		} else if("02".equals(loanType)) {
			SimpleDataDictionary intType = cachedDictionaryService.getCachedDataDic(ywBusinessLoan.getCcol1(), DataDicType.INT_TYPE);
			if(null == intType) {
				ExceptionHelper.thow("999","没有配置取整模式");
			}
			String id = intType.getId();
			DpBaseDataDictionary dpBaseDataDictionary = dpBaseDataDictionaryMapper.selectByPrimaryKey(id);
			String addedValue2 = dpBaseDataDictionary == null ? "0" : dpBaseDataDictionary.getAddedValue2();
			if("ICBC".equals(loanBank)) {
				ywBusinessLoanVoMapper.calculationGx(ywBusinessLoan, intType, addedValue2);
			} else if("TJICBC".equals(loanBank)) {
				ywBusinessLoanVoMapper.calculationTjGx(ywBusinessLoan, intType, addedValue2);
			}
		} else if("05".equals(loanType)) {
			ywBusinessLoanVoMapper.calculationZgYhIntResult(ywBusinessLoan);
		}
	}
	
	/**
	 * 计算银行利率
	 * @param loanMonth
	 * @param loanBank
	 * @return
	 */
	private Double calculationBankRate(Integer loanMonth, String loanBank){
		Double bankRate = 0.00;
		if(12 == loanMonth) {
			if("ICBC".equals(loanBank)) {
				bankRate = (Double)SysParamsType.RATE_BANK_ICBC_12.getDefaultValue();
				String paramValue = baseSysParamsService.getValueByCode(SysParamsType.RATE_BANK_ICBC_12.getCode());
				if(StringUtils.isNotBlank(paramValue)) {
					bankRate = Double.parseDouble(paramValue);
				}
			} else if("BOC".equals(loanBank)) {
				bankRate = (Double)SysParamsType.RATE_BANK_BOC_12.getDefaultValue();
				String paramValue = baseSysParamsService.getValueByCode(SysParamsType.RATE_BANK_BOC_12.getCode());
				if(StringUtils.isNotBlank(paramValue)) {
					bankRate = Double.parseDouble(paramValue);
				}
			}
		} else if(24 == loanMonth) {
			if("ICBC".equals(loanBank)) {
				bankRate = (Double)SysParamsType.RATE_BANK_ICBC_24.getDefaultValue();
				String paramValue = baseSysParamsService.getValueByCode(SysParamsType.RATE_BANK_ICBC_24.getCode());
				if(StringUtils.isNotBlank(paramValue)) {
					bankRate = Double.parseDouble(paramValue);
				}
			} else if("BOC".equals(loanBank)) {
				bankRate = (Double)SysParamsType.RATE_BANK_BOC_24.getDefaultValue();
				String paramValue = baseSysParamsService.getValueByCode(SysParamsType.RATE_BANK_BOC_24.getCode());
				if(StringUtils.isNotBlank(paramValue)) {
					bankRate = Double.parseDouble(paramValue);
				}
			}
		} else if(36 == loanMonth) {
			if("ICBC".equals(loanBank)) {
				bankRate = (Double)SysParamsType.RATE_BANK_ICBC_36.getDefaultValue();
				String paramValue = baseSysParamsService.getValueByCode(SysParamsType.RATE_BANK_ICBC_36.getCode());
				if(StringUtils.isNotBlank(paramValue)) {
					bankRate = Double.parseDouble(paramValue);
				}
			} else if("BOC".equals(loanBank)) {
				bankRate = (Double)SysParamsType.RATE_BANK_BOC_36.getDefaultValue();
				String paramValue = baseSysParamsService.getValueByCode(SysParamsType.RATE_BANK_BOC_36.getCode());
				if(StringUtils.isNotBlank(paramValue)) {
					bankRate = Double.parseDouble(paramValue);
				}
			}
		}
		return bankRate;
	}
	
}
